import express from 'express'
import { render } from './utils'
import proxy from 'express-http-proxy'
import { matchRoutes } from 'react-router-config'
import { getServerStore } from '../store'
import routes from '../Routes'

const app = express()

app.use(express.static('public'))

app.use('/api', proxy('https://www.fastmock.site', {}))




app.get('*', (req, res) => {

    const store = getServerStore(req);

    let matchedRoutes = matchRoutes(routes, req.path);

    let promises = [];

    matchedRoutes.forEach(item => {
        if (item.route.loadData) {
            let p = new Promise((resolve, reject) => {
                item.route.loadData(store).then(resolve).catch(resolve);
            })
            promises.push(p)
        }
    });

    Promise.all(promises).then(() => {
        const context = { css: [] };

        
        let html = render(store, routes, req, context);



        if (context.action == 'REPLACE') {
            //res.redirect(301, context.url)
        } else if (context.NOT_FOUND) {
            res.status(404)
            res.send(html)
        } else {
            res.send(html)
        }







    })


})

app.listen(3000)